package wowmobile;

import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.List;
import java.util.LinkedList;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Random;

public class Database {

        public static Connection con = null;
        public static Statement pst = null;
        public static String user = "root";
        public static String password = "mapa";
        
    public static void RebuildDatabase() { 
        String url = "jdbc:mysql://localhost:3306/";
        try {
            con = DriverManager.getConnection(url, user, password);
            ScriptRunner runner = new ScriptRunner(con, false, true);
            try {
                runner.runScript(new BufferedReader(new FileReader("WOWDB.sql")));
                System.out.println("Database rebuilt");
            } catch (java.io.IOException ex) {
                System.out.println("cos nie tak" + ex);
            }
        } catch (SQLException ex) {
            Logger lgr = Logger.getLogger(Database.class.getName());
            lgr.log(Level.SEVERE, ex.getMessage(), ex);

        } finally {

            try {
                if (pst != null) {
                    pst.close();
                }
                if (con != null) {
                    con.close();
                }

            } catch (SQLException ex) {
                Logger lgr = Logger.getLogger(Database.class.getName());
                lgr.log(Level.SEVERE, ex.getMessage(), ex);
            }
        }
    }

    public static String[] ask(String question, int length) {
        String url = "jdbc:mysql://localhost:3306/WOWDB";
        ResultSet rs = null;
        String[] table = new String[length];
        try {
            con = DriverManager.getConnection(url, user, password);
            pst = con.createStatement();
            rs = pst.executeQuery(question);
            rs = pst.getResultSet();
            String delimiter = "\\,";
            while (rs.next()) {
                table = rs.getString(1).split(delimiter);
            }
        } catch (SQLException ex) {
            Logger lgr = Logger.getLogger(Database.class.getName());
            lgr.log(Level.SEVERE, ex.getMessage(), ex);

        } finally {

            try {
                if (pst != null) {
                    pst.close();
                }
                if (con != null) {
                    con.close();
                }

            } catch (SQLException ex) {
                Logger lgr = Logger.getLogger(Database.class.getName());
                lgr.log(Level.SEVERE, ex.getMessage(), ex);
            }
        }
        return table;
    }
    public static void PlayertoDatabase(PlayerStats stats, Coordinate place, Area area){
        String url = "jdbc:mysql://localhost:3306/WOWDB";
        String query=null;
        try {
            con = DriverManager.getConnection(url, user, password);
            pst = con.createStatement();
            String handitems="";
            for(int i=0;i<stats.getHanditems().size();i++){
                handitems+=stats.getHanditems().get(i).getName()+",";
            }            
            if(handitems.equals("")){
                query="Update Player SET HandItems=null WHERE Id="+stats.getId();
            } else {
                handitems = handitems.substring(0, handitems.length()-1);
                query="Update Player SET HandItems='"+handitems+"' WHERE Id="+stats.getId();
            }
            pst.executeUpdate(query);
            String magic="";
            for(int i=0;i<stats.getMagiclist().size();i++){
                magic+=stats.getMagiclist().get(i).getName()+",";
            }            
            if(magic.equals("")){
                query="Update Player SET MagicList=null WHERE Id="+stats.getId();
            } else {
                magic = magic.substring(0, magic.length()-1);
                query="Update Player SET MagicList='"+magic+"' WHERE Id="+stats.getId();
            }
            pst.executeUpdate(query);
            String wearitems="";
            for(int i=0;i<stats.getWearitems().size();i++){
                wearitems+=stats.getWearitems().get(i).getName() +",";
            }
            if(wearitems.equals("")){
                query="Update Player SET WearItems=null WHERE Id="+stats.getId();
            } else {
                wearitems = wearitems.substring(0, wearitems.length()-1);
                query="Update Player SET WearItems='"+wearitems+"' WHERE Id="+stats.getId();
            }
            pst.executeUpdate(query);
            query="Update Player SET Level="+stats.getLevel()+",Area='"+area.getName()+"',PositionX="+place.getX()+",PositionY="+place.getY()+" WHERE Id="+stats.getId();           
            pst.executeUpdate(query);
            query="Update PlayerClass SET Hp="+stats.getHp()/stats.getLevel()+",Mana="+stats.getMana()/stats.getLevel()+",Defence="+stats.getDefence()/stats.getLevel()+",Speed="+stats.getSpeed()/stats.getLevel()+",Attack="+stats.getAttack()/stats.getLevel()+" WHERE Name='"+stats.getNick()+"'";
            pst.executeUpdate(query);
        } catch (SQLException ex) {
            Logger lgr = Logger.getLogger(Database.class.getName());
            lgr.log(Level.SEVERE, ex.getMessage(), ex);

        } finally {

            try {
                if (pst != null) {
                    pst.close();
                }
                if (con != null) {
                    con.close();
                }

            } catch (SQLException ex) {
                Logger lgr = Logger.getLogger(Database.class.getName());
                lgr.log(Level.SEVERE, ex.getMessage(), ex);
            }
        }
    }
    public static PlayerStats PlayerfromDatabase(String login){
        PlayerStats stats;
        int id,level,image,hp,mana,defence,speed,attack,hpitem,manaitem,defenceitem,speeditem,attackitem,manacostitem,imageitem,poweritem,iditem,positionitem;
        String cname,handitem,magics,wearitem,enemy;
        String[] handitems,magicslist,wearitems;
        boolean enemytarget;
        List<HandItem> handitemlist=new LinkedList<HandItem>();
        List<Magic> magiclist=new LinkedList<Magic>();
        Map<Integer, WearItem> wearitemsmap = new HashMap<Integer, WearItem>();
        float threat;
        id=SelectInt("SELECT Id FROM Player WHERE Name='"+login+"'");
        level=SelectInt("SELECT Level FROM Player WHERE Name='"+login+"'");
        image=SelectInt("SELECT Image FROM Player WHERE Name='"+login+"'");        
        hp=SelectInt("SELECT Hp FROM PlayerClass WHERE Name='"+login+"'");
        mana=SelectInt("SELECT Mana FROM PlayerClass WHERE Name='"+login+"'");
        defence=SelectInt("SELECT Defence FROM PlayerClass WHERE Name='"+login+"'");
        speed=SelectInt("SELECT Speed FROM PlayerClass WHERE Name='"+login+"'");
        attack=SelectInt("SELECT Attack FROM PlayerClass WHERE Name='"+login+"'");
        threat=SelectFloat("SELECT Threat FROM PlayerClass WHERE Name='"+login+"'");       
        cname=SelectString("SELECT ClassName FROM PlayerClass WHERE Name='"+login+"'");
        handitem=SelectString("SELECT HandItems FROM Player WHERE Name='"+login+"'");
        magics=SelectString("SELECT MagicList FROM Player WHERE Name='"+login+"'");
        wearitem=SelectString("SELECT WearItems FROM Player WHERE Name='"+login+"'");
        if (handitem!=null){
            handitems=handitem.split(",");
            for (int i=0;i<handitems.length;i++){
                hpitem=SelectInt("SELECT Hp FROM Items WHERE Name='"+handitems[i]+"'");
                manaitem=SelectInt("SELECT Mana FROM Items WHERE Name='"+handitems[i]+"'");
                defenceitem=SelectInt("SELECT Defence FROM Items WHERE Name='"+handitems[i]+"'");
                speeditem=SelectInt("SELECT Speed FROM Items WHERE Name='"+handitems[i]+"'");
                attackitem=SelectInt("SELECT Attack FROM Items WHERE Name='"+handitems[i]+"'");
                handitemlist.add(i,new HandItem(handitems[i],hpitem,manaitem,defenceitem,attackitem,speeditem));
            }
        } else {
            handitemlist=null;
        }
        if (magics!=null){
            magicslist=magics.split(",");
            for (int i=0;i<magicslist.length;i++){
                hpitem=SelectInt("SELECT Hp FROM Magic WHERE Name='"+magicslist[i]+"'");
                manaitem=SelectInt("SELECT Mana FROM Magic WHERE Name='"+magicslist[i]+"'");
                defenceitem=SelectInt("SELECT Defence FROM Magic WHERE Name='"+magicslist[i]+"'");
                speeditem=SelectInt("SELECT Speed FROM Magic WHERE Name='"+magicslist[i]+"'");
                attackitem=SelectInt("SELECT Attack FROM Magic WHERE Name='"+magicslist[i]+"'");
                manacostitem=SelectInt("SELECT ManaCost FROM Magic WHERE Name='"+magicslist[i]+"'");
                imageitem=SelectInt("SELECT Image FROM Magic WHERE Name='"+magicslist[i]+"'");
                enemy=SelectString("SELECT EnemyTarget FROM Magic WHERE Name='"+magicslist[i]+"'");
                if(enemy.equals("false")){
                    enemytarget=false;
                } else {
                    enemytarget=true;
                }
                magiclist.add(i,new Magic(magicslist[i],enemytarget,hpitem,manaitem,defenceitem,attackitem,speeditem,manacostitem,imageitem));
            }
        } else {
            handitemlist=null;
        }
        if (wearitem!=null){
            wearitems=wearitem.split(",");
            for (int i=0;i<wearitems.length;i++){
                hpitem=SelectInt("SELECT Hp FROM Items WHERE Name='"+wearitems[i]+"'");
                poweritem=SelectInt("SELECT Power FROM Items WHERE Name='"+wearitems[i]+"'");
                iditem=SelectInt("SELECT Id FROM Items WHERE Name='"+wearitems[i]+"'");
                manaitem=SelectInt("SELECT Mana FROM Items WHERE Name='"+wearitems[i]+"'");
                defenceitem=SelectInt("SELECT Defence FROM Items WHERE Name='"+wearitems[i]+"'");
                speeditem=SelectInt("SELECT Speed FROM Items WHERE Name='"+wearitems[i]+"'");
                attackitem=SelectInt("SELECT Attack FROM Items WHERE Name='"+wearitems[i]+"'");
                imageitem=SelectInt("SELECT Image FROM Items WHERE Name='"+wearitems[i]+"'");
                positionitem=SelectInt("SELECT Position FROM Items WHERE Name='"+wearitems[i]+"'");
                wearitemsmap.put(i,new WearItem(wearitems[i],iditem,poweritem,hpitem,manaitem,speeditem,attackitem,defenceitem,imageitem,positionitem));
            }
        } else {
            handitemlist=null;
        }
        stats=new PlayerStats(id,login,level,new PlayerClass(cname,hp,mana,defence,speed,attack,threat),handitemlist,wearitemsmap,magiclist,image);
        return stats;
    }
    
    public static Coordinate CoordinatefromDatabase(String login){
        Coordinate place;
        int posX,posY;
        posX=SelectInt("SELECT PositionX FROM Player WHERE Name='"+login+"'");
        posY=SelectInt("SELECT PositionY FROM Player WHERE Name='"+login+"'");
        place=new Coordinate(posX,posY);
        return place;
    }
    
    public static Area AreaFromDatabase(String login){
        Area area;
        String map;
        map=SelectString("SELECT Area FROM Player WHERE Name='"+login+"'");
        area=new Area(map);
        return area;
    }
    
    public static int SelectInt (String query){
        ResultSet rs;
        int result=0;
        String url = "jdbc:mysql://localhost:3306/WOWDB";
        try {
            con = DriverManager.getConnection(url, user, password);
            pst = con.createStatement();
            rs=pst.executeQuery(query);
            while (rs.next()) {
                result = rs.getInt(1);
            }
        } catch (SQLException ex) {
            Logger lgr = Logger.getLogger(Database.class.getName());
            lgr.log(Level.SEVERE, ex.getMessage(), ex);

        } finally {

            try {
                if (pst != null) {
                    pst.close();
                }
                if (con != null) {
                    con.close();
                }

            } catch (SQLException ex) {
                Logger lgr = Logger.getLogger(Database.class.getName());
                lgr.log(Level.SEVERE, ex.getMessage(), ex);
            }
        }
        return result;
    }
    public static float SelectFloat (String query){
        ResultSet rs;
        float result=0;
        String url = "jdbc:mysql://localhost:3306/WOWDB";
        try {
            con = DriverManager.getConnection(url, user, password);
            pst = con.createStatement();
            rs=pst.executeQuery(query);
            while (rs.next()) {
                result = rs.getFloat(1);
            }
        } catch (SQLException ex) {
            Logger lgr = Logger.getLogger(Database.class.getName());
            lgr.log(Level.SEVERE, ex.getMessage(), ex);

        } finally {

            try {
                if (pst != null) {
                    pst.close();
                }
                if (con != null) {
                    con.close();
                }

            } catch (SQLException ex) {
                Logger lgr = Logger.getLogger(Database.class.getName());
                lgr.log(Level.SEVERE, ex.getMessage(), ex);
            }
        }
        return result;
    }
    public static String SelectString (String query){
        ResultSet rs;
        String result=null;
        String url = "jdbc:mysql://localhost:3306/WOWDB";
        try {
            con = DriverManager.getConnection(url, user, password);
            pst = con.createStatement();
            rs=pst.executeQuery(query);
            while (rs.next()) {
                result = rs.getString(1);
            }
        } catch (SQLException ex) {
            Logger lgr = Logger.getLogger(Database.class.getName());
            lgr.log(Level.SEVERE, ex.getMessage(), ex);

        } finally {

            try {
                if (pst != null) {
                    pst.close();
                }
                if (con != null) {
                    con.close();
                }

            } catch (SQLException ex) {
                Logger lgr = Logger.getLogger(Database.class.getName());
                lgr.log(Level.SEVERE, ex.getMessage(), ex);
            }
        }
        return result;
    }
    
    public static boolean CheckLogin(String login){
        boolean isLogin=false;
        String url = "jdbc:mysql://localhost:3306/WOWDB";
        ResultSet rs = null;
        try {
            con = DriverManager.getConnection(url, user, password);
            pst = con.createStatement();
            String query="SELECT Id FROM Player WHERE Name='"+login+"'";
            rs = pst.executeQuery(query);
            while (rs.next()) {
                isLogin=true;
                break;
            }
        } catch (SQLException ex) {
            Logger lgr = Logger.getLogger(Database.class.getName());
            lgr.log(Level.SEVERE, ex.getMessage(), ex);

        } finally {

            try {
                if (pst != null) {
                    pst.close();
                }
                if (con != null) {
                    con.close();
                }

            } catch (SQLException ex) {
                Logger lgr = Logger.getLogger(Database.class.getName());
                lgr.log(Level.SEVERE, ex.getMessage(), ex);
            }
        }
        return isLogin;
    }
    
    public static ArrayList<Monster> getMonster(String area){
        int id,level,image,hp,mana,defence,speed,attack;
        String name;
        String monsters[]=new String[10];
        ArrayList<Monster> mon = new ArrayList<Monster>();
        monsters=ask("SELECT Monster FROM Environment WHERE Name='"+area+"'",10);
        for (int i=0;i<monsters.length;i++){
            name=monsters[i];
            id=SelectInt("SELECT Id FROM Monster WHERE Name='"+name+"'");
            level=SelectInt("SELECT Level FROM Monster WHERE Name='"+name+"'");
            image=SelectInt("SELECT Image FROM Monster WHERE Name='"+name+"'");
            hp=SelectInt("SELECT MaxHp FROM Monster WHERE Name='"+name+"'");
            mana=SelectInt("SELECT MaxMana FROM Monster WHERE Name='"+name+"'");
            defence=SelectInt("SELECT Defence FROM Monster WHERE Name='"+name+"'");
            speed=SelectInt("SELECT Speed FROM Monster WHERE Name='"+name+"'");
            attack=SelectInt("SELECT Attack FROM Monster WHERE Name='"+name+"'");
            Monster monster=new Monster(id,name,level,hp,mana,speed,attack,defence,image);
            mon.add(monster);
        }
        return mon;
    }
    
    public static Quest getQuest(String name){
        String description,item,environment;
        int howMany;
        Quest quest;
        description=SelectString("SELECT Description FROM Quest WHERE Name='"+name+"'");
        item=SelectString("SELECT Item FROM Quest WHERE Name='"+name+"'");
        environment=SelectString("SELECT Environment FROM Quest WHERE Name='"+name+"'");
        howMany=SelectInt("SELECT HowMany FROM Quest WHERE Name='"+name+"'");
        Random r=new Random();
        ArrayList<Monster> monsters = getMonster(environment);
        Monster monster = monsters.get(r.nextInt(monsters.size()));
        if (item!=null){
            quest=new Quest(name,description,howMany,monster,item);
        } else {
            quest=new Quest(name,description,howMany,monster);
        }
        return quest;
    }
}
